package com.game.battle.start;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.battle.service.server.ServerService;
import com.game.common.Transmitter;
import com.game.common.config.BaseServerConfig;
import com.game.core.net.server.SimpleClient;
import com.game.core.net.server.SimpleSSNettyInitializer;
import com.game.core.net.server.SimpleServer;
import com.game.core.service.ServiceContainer;

public class NetInitializer
{
	private Logger logger = LoggerFactory.getLogger(NetInitializer.class);
	
	private SSMessageInitializer ssMsgInitializer;
	private SimpleSSNettyInitializer ssInitializer;
	private SimpleClient bgClient;
	
	// 作为服务端等待Gateway连接,交互协议使用SS进行。
	private SSMessageInitializer csMsgInitializer;
	private SimpleSSNettyInitializer csInitializer;
	private SimpleServer gbServer;
	
	public void init() throws Exception
	{
		ssMsgInitializer = new SSMessageInitializer("com.game.battle.action");
		ssMsgInitializer.initialize();
		ssInitializer = new SimpleSSNettyInitializer(ssMsgInitializer);
		bgClient = new SimpleClient();
		bgClient.initialize(ssInitializer, ssMsgInitializer);
		
		csMsgInitializer = new SSMessageInitializer("com.game.battle.action");
		csMsgInitializer.initialize();
		csInitializer = new SimpleSSNettyInitializer(csMsgInitializer);
		gbServer = new SimpleServer();
		gbServer.initialize(csInitializer, csMsgInitializer);
		
		Transmitter.getInstance().setMessageInitializer(ssMsgInitializer);
	}
	
	public void connectToGame()
	{
		ServerService service = ServiceContainer.getInstance().getPublicService(ServerService.class);
		BaseServerConfig config = service.getServerConfig();
		boolean ret = bgClient.connectTo(config.getManageServerAddress(), 5);
		if (ret == false) {
			logger.error("Connect To GameServer Filed!");
		}
	}
	
	public void openPort4Client(int port)
	{
		boolean ret = gbServer.openPort(new InetSocketAddress(port));
		if (ret == false) {
			logger.error("Open Port Filed! port:{}",port);
		}
		logger.info("Begin to open port:{} for client", port);
	}
}
